﻿using LongGi.TingkatKebocoranModule.CommModel;
using LongGi.TingkatKebocoranModule.Views;
using LPLS.DBEntities.LongGIModule;
using LPLS.DBInterface.LongGiMoudle;
using LPLS.PluginCommon;
using LPLS.PluginCommon.ModulePlugin;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace LongGi.TingkatKebocoranModule.ViewModels
{
    [ViewModelMetadata(projectID: "12322222", viewModelName: "隆基数据统计模块", version: "1.0.1", lifecycle: Lifecycle.Singleton, index: 0, isCommon: true)]

    public  class TKMianViewModel : ViewModelBase
    {
        private ObservableCollection<TabItem> _tabItems;

        private IKaJiangDataService KaJiangDbService;
        private ILoulvDataService LoulvDbService;

        public TKMianViewModel(
            IContainerProvider containerProvider,
            IKaJiangDataService kaJiangDbService,
            ILoulvDataService loulvDataService

            ) 
            : base(containerProvider)
        {
            InitializeTabs();
            this.KaJiangDbService = kaJiangDbService;
            this.LoulvDbService = loulvDataService;

            IsReadFiles = true;
            TechnologyPathList = new ObservableCollection<string>();
            OpenFiles = new DelegateCommand(LoadData);
            QuaryCommand = new DelegateCommand(Query);
            ExportCommand = new DelegateCommand(ExportData);
            TechnologyList = new ObservableCollection<ExcelFileHeaderModel>();
            this.EndDate = DateTime.Now.AddDays(1);
            this.StartDate = DateTime.Now.AddDays(-1);
            LoadTubes();
        }

        public ObservableCollection<TabItem> TabItems
        {
            get { return _tabItems; }
            set { SetProperty(ref _tabItems, value); }
        }

        private void InitializeTabs()
        {
            TabItems = new ObservableCollection<TabItem>
        {
            CreateTabItem("炉管漏率检测", typeof(TKChartView)),
            CreateTabItem("扭矩监控", typeof(PaddleCheckView)),
            //CreateTabItem("报警代码规则配置", typeof(AlarmVarableCodeRuleConfigView)),

        };
        }


        #region 主业务逻辑


        private DateTime _StartTime;
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartDate
        {
            get { return _StartTime; }
            set { SetProperty(ref _StartTime, value); }
        }

        private DateTime _EndTime;
        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime EndDate
        {
            get { return _EndTime; }
            set { SetProperty(ref _EndTime, value); }
        }


        #region  Command
        /// <summary>
        /// 打开文件
        /// </summary>
        public DelegateCommand OpenFiles { get; }

        /// <summary>
        /// 查询指令
        /// </summary>
        public DelegateCommand QuaryCommand { get; }



        public DelegateCommand ExportCommand { get; }
        private List<KaJiangData> _KajiangData = new List<KaJiangData>();
        private List<LoulvData> _LoulvData = new List<LoulvData>();

      




        private void LoadData()
        {
            LoadTubes();

        }
        private void Query()
        {
            Message = "正在查询请稍后!";
            if (IsQuarying)
            {
                Message = "正在查询，请勿重复点击!";
                return;
            }
            IsQuarying = true;
          
            Thread t = new Thread( () => {

                _KajiangData.Clear();
                _LoulvData.Clear();
                var startime = this.StartDate;
                var entime = this.EndDate;
                var gongyi = SelectTechnologyPath;
                var kajiangdata = KaJiangDbService.GetData(gongyi, SelectTube,startime,entime);

                _KajiangData = kajiangdata;

                LongGiEventCommon.PubshKajiangDataHander(_KajiangData);


                _LoulvData.Clear();

                var loulvdata= LoulvDbService.GetData(gongyi, SelectTube, startime, entime);

                _LoulvData = loulvdata;

                LongGiEventCommon.PubshLoulvDataHander(_LoulvData);

                Message = $"查询完成! 一共{_LoulvData.Count} 个工艺数";
                if (string.IsNullOrEmpty(SelectTechnologyPath))
                {

                    Message = "未选工艺";
                    return;
                }
              
              


           
                IsQuarying = false;

            });
            t.IsBackground = true;
            t.Start();
        }


        private void ExportData() 
        {

            LongGiEventCommon.PublishExportExcelDataHander();

        }
        #endregion



        //  private List<ExcelFileHeaderModel> _PublishData = new List<ExcelFileHeaderModel>();


        /// <summary>
        /// 加载 炉管
        /// </summary>
        private void LoadTubes()
        { 
        
        
           var data= GetTubes();
            Tubes = new ObservableCollection<string>(data);

            TechnologyPathList =new ObservableCollection<string>( LoulvDbService.GetGongyi());


        }

        public static string[] GetTubes()
        {
            // 获取生成目录下的 JSON 文件路径
            var baseDir = AppContext.BaseDirectory;
            var configPath = Path.Combine(baseDir,"LongGi.json");

            if (!File.Exists(configPath))
                throw new FileNotFoundException("配置文件未找到: " + configPath);

            // 读取并解析 JSON
            var json = File.ReadAllText(configPath);
            using var doc = JsonDocument.Parse(json);
            var tubesString = doc.RootElement.GetProperty("Tubes").GetString();

            // 按逗号分割为数组
            return tubesString?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
        }

        #region 属性
        private ObservableCollection<string> _TechnologyPathList;

        public ObservableCollection<string> TechnologyPathList
        {
            get { return _TechnologyPathList; }
            set
            {

                SetProperty(ref _TechnologyPathList, value);

            }
        }
        private bool _IsReadFiles;
        public bool IsReadFiles
        {
            get { return _IsReadFiles; }
            set { SetProperty(ref _IsReadFiles, value); }
        }




        private ObservableCollection<string> _Tubes;

        public ObservableCollection<string> Tubes
        {
            get { return _Tubes; }
            set {
                SetProperty(ref _Tubes, value);

              }
        }

        private string _SelectTube;

        public string SelectTube
        {
            get { return _SelectTube; }
            set 
            {
                
               
                SetProperty(ref _SelectTube, value);
              }
        }



        Timer _Timer;

        private ObservableCollection<ExcelFileHeaderModel> _TechnologyList;
        /// <summary>
        /// 存储工艺的集合
        /// </summary>
        public ObservableCollection<ExcelFileHeaderModel> TechnologyList
        {
            get { return _TechnologyList; }
            set { SetProperty(ref _TechnologyList, value); }
        }


        private string _Message;
        public string Message
        {
            get { return _Message; }
            set { SetProperty(ref _Message, value); }
        }


        private string _SelectTechnologyPath;
        /// <summary>
        /// 选择工艺
        /// </summary>
        public string SelectTechnologyPath
        {
            get { return _SelectTechnologyPath; }
            set { SetProperty(ref _SelectTechnologyPath, value); }
        }



        #endregion





        #region 字段

        private List<string> alreadyRead = new List<string>();

        private List<string> FullPaths = new List<string>();
        /// <summary>
        /// 字段集合
        /// </summary>
        public List<string> FilteredFilesPath = new List<string>();

        private bool IsQuarying = false;
        #endregion




        #region 函数
        private float GetRateOfLeakageValue(DataTable dt)
        {
            var lastdata = dt.Rows[dt.Rows.Count - 1];

            var value = float.Parse(lastdata["漏率"].ToString());
            return value;

        }
        #endregion
        #endregion











    }
}
